<script setup lang="ts">
import { getConsultOrderPre, createConsultOrder } from '@/services/consult'
import { getPatientDetail } from '@/services/user'
import { useStore } from '@/stores'
import type { ConsultOrderPreData } from '@/types/consult'
import type { Patient } from '@/types/user'
import { showConfirmDialog, showDialog, showToast } from 'vant'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { onBeforeRouteLeave } from 'vue-router'
const { consult } = useStore()
const orderPre = ref<ConsultOrderPreData>()
const patientInfo = ref<Patient>()
const router = useRouter()
// 并发获取预支付信息和患者信息, 并存储
const getData = async () => {
  // 刷新页面提示
  if (!consult.consult.type) {
    return showDialog({
      title: '温馨提示',
      message: '支付信息不完整请重新填写，如果未支付可以去记录继续支付'
    }).then(() => {
      // on close
      router.replace('/')
    })
  }
  Promise.all([
    getConsultOrderPre({
      type: consult.consult.type,
      illnessType: consult.consult.illnessType
    }),
    getPatientDetail(consult.consult.patientId as string)
  ]).then((vals) => {
    orderPre.value = vals[0].data
    patientInfo.value = vals[1].data

    // 设置优惠券id
    consult.setCouponId(vals[0].data.couponId)
  })
}
getData()
const isAgree = ref(false)

const orderId = ref('')
// 立即支付展示一个抽屉  生成一个订单id
const submit = async () => {
  // 1. 勾选支付协议
  if (!isAgree.value) return showToast('请勾选支付协议')
  // 2. 展示一个抽屉
  show.value = true
  // 3. 创建订单id
  const res = await createConsultOrder(consult.consult)
  // console.log(res)
  // 4. 记录订单id
  orderId.value = res.data.id
  // 5. 清除 consult模块中之前记录的consult所有信息
  consult.clear()
}
// 组件内的路由守卫  return false阻止离开当前页面
onBeforeRouteLeave(() => {
  // 生成订单id后阻止离开当前页面
  if (orderId.value) return false
})

const show = ref(false) // 控制抽屉的布尔值
// 阻止抽屉关闭
const beforeClose = () => {
  return showConfirmDialog({
    title: '关闭支付',
    message: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
    confirmButtonText: '继续支付',
    cancelButtonText: '仍要关闭'
  })
    .then(() => {
      return false // 取消关闭抽屉
    })
    .catch(() => {
      //跳转之前清空 orderId , 因为 路由守卫会拦截
      orderId.value = ''
      // 跳转到问诊记录列表页面
      router.replace('/user/consult')
      return true //  不写也可以, 但是会报类型的问题
    })
}
</script>

<template>
  <cp-pay-sheet
    v-model:show="show"
    :orderId="orderId"
    :actualPayment="orderPre?.actualPayment!"
    :before-close="beforeClose"
    callback="/room"
  ></cp-pay-sheet>

  <div class="consult-pay-page" v-if="orderPre && patientInfo">
    <cp-nav-bar title="支付" />
    <div class="pay-info">
      <p class="tit">图文问诊{{ orderPre.payment }}元</p>
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p class="desc">
        <span>极速问诊</span>
        <span>自动分配医生</span>
      </p>
    </div>
    <van-cell-group>
      <van-cell title="优惠券" :value="`-¥${orderPre.couponDeduction}.00`" />
      <van-cell title="积分抵扣" :value="`-¥${orderPre.pointDeduction}.00`" />
      <van-cell
        title="实付款"
        :value="`-¥${orderPre.actualPayment}.00`"
        class="pay-price"
      />
    </van-cell-group>
    <div class="pay-space"></div>
    <van-cell-group>
      <van-cell
        title="患者信息"
        :value="`${patientInfo.name} | ${patientInfo.genderValue} | ${patientInfo.age}岁`"
      ></van-cell>
      <van-cell
        title="病情描述"
        :label="`${consult.consult.illnessDesc}`"
      ></van-cell>
    </van-cell-group>
    <div class="pay-schema">
      <van-checkbox v-model="isAgree"
        >我已同意 <span class="text">支付协议</span></van-checkbox
      >
    </div>
    <van-submit-bar
      button-type="primary"
      :price="orderPre.actualPayment * 100"
      button-text="立即支付"
      text-align="left"
      @click="submit"
    />
  </div>
  <div class="consult-pay-page" v-else>
    <cp-nav-bar title="支付" />
    <van-skeleton :row="3" />
    <van-skeleton :row="5" style="margin: 20px 0" />
    <van-skeleton :row="3" style="margin: 10px 0" />
    <van-skeleton :row="5" />
  </div>
</template>

<style lang="scss" scoped>
.consult-pay-page {
  padding: 46px 0 50px 0;
}
.pay-info {
  display: flex;
  padding: 15px;
  flex-wrap: wrap;
  align-items: center;
  .tit {
    width: 100%;
    font-size: 16px;
    margin-bottom: 10px;
  }
  .img {
    margin-right: 10px;
    width: 38px;
    height: 38px;
    border-radius: 4px;
    overflow: hidden;
  }
  .desc {
    flex: 1;
    > span {
      display: block;
      color: var(--cp-tag);
      &:first-child {
        font-size: 16px;
        color: var(--cp-text2);
      }
    }
  }
}
.pay-price {
  ::v-deep() {
    .vam-cell__title {
      font-size: 16px;
    }
    .van-cell__value {
      font-size: 16px;
      color: var(--cp-price);
    }
  }
}
.pay-space {
  height: 12px;
  background-color: var(--cp-bg);
}
.pay-schema {
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  .text {
    color: var(--cp-primary);
  }
}
</style>
